package com.cpu.z80.stack;

/**
 * This is the Stack-Class!
 * @author kennux
 */

import java.util.Arrays;

public class Stack {
    private int[] stack;
    /**
     * Push a variable on the stack
     * @param register variable to push on
     */
    public void push(int register) {

        int[] temp = stack.clone(); // Clone current stack!

        stack = new int[stack.length + 1]; // New field for new variable

        for(int i = 0; i < temp.length; i++) { // For filling in the old variables
            stack[i] = temp[i]; // Fill in
        }

        stack[stack.length-1] = register; // Fill in the new variable
    }
    /**
     * Pop a varible from the stack
     * @return The last pushed variable from stack
     */
    public int pop() {
        try {
            int ret = stack[stack.length-1]; // Get return variable

            int[] temp = stack.clone(); // Clone Stack
            stack = Arrays.copyOf(temp, stack.length - 1); // Fill in Stack

            return ret; // Return :>
        } catch (java.lang.ArrayIndexOutOfBoundsException e) {
            System.out.println("Stack.java - pop() error");
            System.out.println("Tried to get object from clear stack! Returning 0");
            return 0;
        } catch (Exception e) {
            System.out.println("Stack.java - pop() error");
            System.out.println("Unknown error! Returning 0 and printing StackTrace:");
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * Initializes the stack!
     */
    public Stack() {
        stack = new int[0]; // New Stack-Array
    }
}
